<template>
  <div>
    <div>
      <div class="cards">
        <el-button type="primary" style="margin-right: 10px" @click="handleAdd">+ 新增</el-button>
        <el-button type="warning" style="margin-right: 20px" @click="delBatch">批量删除</el-button>
        <el-input style="width:240px;margin-right: 10px; text-align: center" v-model="data.name" placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="primary" @click="rest">重 置</el-button>
      </div>
      <!--数据表-->
      <div class="card" style="margin-top: 10px">
        <el-table :data="data.tableData"  @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection"  style="border: #666666; width:10px"></el-table-column>
          <el-table-column label="名称" prop="name"/>
          <el-table-column label="状态">
            <template #default="scope">
              <span>{{ scope.row.status? '激活' : '禁用' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" style="padding: 5px 8px">编辑</el-button>
              <el-button @click="handleDelete(scope.row)" type="danger" :icon="Delete" style="padding: 5px 8px">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-pagination
              @current-change="load"
              @size-change="load"
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              :page-sizes="[5,10,15,20]"
              background
              layout="total,sizes,prev,pager,next,jumper"
              :total="data.total"
          ></el-pagination>
        </div>
      </div>
      <!--新增-->
      <el-dialog v-model="data.formVisible" title="新增用户信息" width="500">
        <el-form :model="data.form" style=" width:400px;display: flex;flex-direction: column;align-items: center;margin-left: 25px;">
          <el-form-item label="名称：">
            <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="状态：">
            <el-radio-group v-model = "data.form.status" style="width: 178px">
              <el-radio value="激活" label="激活" style="margin-left: 8px"></el-radio>
              <el-radio value="禁用" label="禁用"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">
              保 存
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import {Search,Delete,Edit} from "@element-plus/icons-vue"
import { ref } from 'vue'
import request from '@/utils/request.js';
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name:null,
  tableData:[],
  pageNum:1,
  pageSize:10,
  total:0,
  userList:[],
  formVisible:false,
  form:[],
  ids:[],
})

const load = () => {
  request.get('/category/findAllCategory',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
    }
  }).then(res => {
    data.tableData = res.data.data
    data.total = res.data.total
  })
}
load()

//重置
const rest = () => {
  data.name = null
  load()
}

//新增
const handleAdd = () => {
  data.formVisible = true
  data.form = {}
}

// 将状态值转换为布尔类型
const convertStatusToBoolean = (form) => {
  if (form.status === '激活') {
    form.status = true;
  } else if (form.status === '禁用') {
    form.status = false;
  }
  return form;
}

const save = () => {
  data.form.id ? update() : add()
}

const add = () => {
  const formData = convertStatusToBoolean({...data.form}); // 转换状态值
  request.post('category/addType', formData).then(res => {
    if(res.code === 200){
      data.formVisible = false;
      ElMessage.success("添加成功")
      load()
    }else{
      ElMessage.error(res.message)
    }
  })
}

//编辑
const update = () => {
  const formData = convertStatusToBoolean({...data.form}); // 转换状态值
  request.put('category/updateType', formData).then(res => {
    if(res.code === 200){
      data.formVisible = false;
      ElMessage.success("修改成功")
      load()
    }else{
      ElMessage.error(res.message)
    }
  })
}

//删除
const handleDelete = (row) =>{
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？','温馨提示',{type:'warning'}).then(() => {
    request.delete('category/deleteType/'+row.id).then(res => {
      if(res.code === 200 && row.status){
        ElMessage.success("删除成功")
        load()
      }else{
        ElMessage.warning('已经被禁用，不可以进行删除')
      }
    })
  }).catch()
}

//编辑
const handleUpdate = (row) =>{
  if(row.status){
    data.form = JSON.parse(JSON.stringify(row)) //深拷贝
    data.formVisible = true
  }else {
    ElMessage.warning('已经被禁用，不可以进行修改')
  }

}

//多选
const handleSelectionChange =(rows) =>{
  console.log(rows)
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

//批量删除
const delBatch = () => {
  if(data.ids.length === 0){
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？','温馨提示',{type:'warning'}).then(() => {
    request.delete('category/deleteBatchType',{data:data.ids}).then(res => {
      if(res.code === 200){
        ElMessage.success("删除成功")
        load()
      }else{
        ElMessage.error(res.message)
      }
    })
  }).catch()

}

const value = ref('')
</script>

<style scoped>
.cards{
  background-color: white;
  padding: 10px;
  border-radius: 5px ;
  box-shadow:0 0 8px rgba(0,0,0,.12) ;
}
</style>